<?php
namespace app\index\controller;

use think\Controller;
use think\Model;

class Index extends Controller
{
    protected  $city;
    public function __construct()
    {
        parent::__construct();
        $this->city= $this->getAddress();
        $this->assign("action",request()->action());
    }
    public function index()
    {

        $banner=db("banner")
            //->cache(true)
            ->where(['status'=>1])->order("sort desc")->select();
        $about=db("about_us")
          //  ->cache(true)
            ->find();
        $case=db("server_case")->where(['status'=>1])
           // ->cache(true)
            ->select();
        return $this->fetch("index",compact("banner","about",'case'));
    }
    //四大模块
    public function service()
    {
        $cate_id=input("id");
        $catelist=db("server_category")
            //->cache(true)
            ->where(['status'=>1])->order("sort desc")->select();
        if(!$cate_id){
            $cate_id=$catelist[0]['id'];
        }
        $cate=db("server_category")
            //->cache(true)
            ->where(['id'=>$cate_id])->find();
        $list=db("server")
            //->cache(true)
            ->where(['status'=>1,'cate_id'=>$cate_id])->order("id desc")->select();
        return $this->fetch("service",compact("list",'cate','catelist'));
    }
    public function news()
    {
        $cate_id=input("id");
        $catelist=db("news_category")
            //->cache(true)
            ->where(['status'=>1])->order("sort desc")->select();
        if(!$cate_id){
            $cate_id=$catelist[0]['id'];
        }
        $cate=db("news_category")
            //->cache(true)
            ->where(['id'=>$cate_id])->find();
        $list=db("news")
            //->cache(true)
            ->where(['status'=>1,'cate_id'=>$cate_id])->order("id desc")->paginate(5);
        return $this->fetch("news",compact("list",'cate','catelist'));
    }
    public function news_detail()
    {
        $id=input("id");
        $news=db("news")
            //->cache(true)
            ->where(['status'=>1,'id'=>$id])->find();
        $catelist=db("news_category")
            //->cache(true)
            ->where(['status'=>1])->order("sort desc")->select();
            $cate_id=$news['cate_id'];
        $cate=db("news_category")
            //->cache(true)
            ->where(['id'=>$cate_id])->find();
        $news['content']=htmlspecialchars_decode($news['content']);
        return $this->fetch("news_detail",compact("news",'cate','catelist'));
    }
    public function contact()
    {
        if(request()->isPost()){
            $data=input();
            unset($data['/index/index/contact_html']);
            if(!$data['name']){
                return $this->renderError('姓名必填');
            }
            if(!$data['mobile']){
                return $this->renderError('手机号码必填');
            }
            if(!$data['content']){
                return $this->renderError('内容不能为空');
            }
            if(!check_mobile($data['mobile'])){
                return $this->renderError('不是有效的手机号码');
            }
            $data['ip']=request()->ip();
            $con=db("contact_us")->where(['ip'=>$data['ip']])
            ->whereTime('create_time', 'today')
          //      ->fetchSql(true)
            ->count();
            if($con>=2){
                return $this->renderError('每个IP每天最多可以留言2次');
            }
            $data['address']=$this->city;
            $data['create_time']=time();
            $res=db("contact_us")->insert($data);
            if($res) {
                return $this->renderSuccess("提交成功");
            }else{
                return $this->renderError("提交失败");
            }
        }
        return $this->fetch("contact",compact("news",'cate','catelist'));
    }

    private function getAddress()
    {
        $ip=request()->ip();
        $url = "http://api.map.baidu.com/location/ip?ak=".BAIDU_AK."&ip=$ip&coor=bd09ll";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        if(curl_errno($ch))
        { echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);}
        curl_close($ch);
        $info = json_decode($output, true);
        if($info['status'] == "0"){
            $city = $info['content']['address'];
            if(!db("view_record")->where(['ip'=>$ip])->find()){
                $insert['ip']=$ip;
                $insert['city']=$city;
                $insert['create_time']=time();
                db("view_record")->insert($insert);
            }
          return $city;
        }

    }


    public function renderSuccess($msg = 'success', $url = '', $data = [])
    {
        return $this->renderJson(1, $msg, $url, $data);
    }
    public function renderError($msg = 'error', $url = '', $data = [])
    {
        return $this->renderJson(0, $msg, $url, $data);
    }
    /**
     * 返回封装后的 API 数据到客户端
     * @param int $code
     * @param string $msg
     * @param string $url
     * @param array $data
     * @return array
     */
    protected function renderJson($code = 1, $msg = '', $url = '', $data = [])
    {
        return compact('code', 'msg', 'url', 'data');
    }



    public function auth()
    {
        $file = './5555.png';
        if($fp = fopen($file,"rb", 0))
        {
            $gambar = fread($fp,filesize($file));
            fclose($fp);
            $base64 = chunk_split(base64_encode($gambar));

//{"code":0,"message":"操作成功","data":{"name":"马开林","idCardNumber":"532625198603081519","gender":"男","birthday":"1986-03-08","race":"回","address":"云南省文山壮族苗族自治州马关县八寨镇八寨村民委横街小组91号","side":null,"type":1,"issuedBy":null,"validDate":null,"verifyCode":1,"verifyDesc":"认证成功"}}
            $host = "http://idcardv.market.alicloudapi.com";
            $path = "/clouds/ocrVerify/idcardVerify";
            $method = "POST";
            $appcode = "f9c2083bcfe6427babe024b1f1b7afc1";
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appcode);
            //根据API的要求，定义相对应的Content-Type
            array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
            $querys = "";
            $data['humanImageBase64']=$base64;
            $bodys =json_encode($data);// "{\"humanImageBase64\":\"/9j/4SXvRXhpZgAATU0AKgAAAAgACgEP......AAIAAAAHAAAAAAA==\"//人像面图片base64编码}";
            $url = $host . $path;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, true);
            if (1 == strpos("$".$host, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
            $response=curl_exec($curl);
            var_dump($response);
            if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
                $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
                $header = substr($response, 0, $headerSize);
                $body = substr($response, $headerSize);
                echo '<pr>';
                var_dump($body);

                var_dump(json_decode($body,true));
                //var_dump($header);
            }else{
                echo 2222;
            }

        }
        exit;
    }

}
